package org.diysearch.tools;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.diysearch.helpers.LinkHelper;
import org.diysearch.models.Link;

/**
 * Create/re-fresh the solr/lucene index with terms in our database
 * 
 * @author dpalmer
 * 
 */
public class Indexer {
	private static final Log LOG = LogFactory.getLog(Indexer.class);

	/**
	 * Main - start up this program
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// lets get our links to index
		List<Link> results = LinkHelper.fetchLinks(args);
		LOG.info("Indexing: " + results.size() + " links for this run");
		for (Link link : results) {
			String[] tags = { "" };
			int tagCount = link.getTags().size();
			if (tagCount > 0) {
				tags = new String[tagCount];
				for (int i = 0; i < tagCount; i++) {
					tags[i] = link.getTags().get(i).getName();
				}
			}
			link.set_tags(tags);
			try {
				UpdateResponse rsp = BaseTool.SOLR_SERVER.addBean(link);
				//UpdateResponse rsp = BaseTool.SOLR_SERVER.deleteByQuery("TEST");
				BaseTool.SOLR_SERVER.commit(true, true);
				int status = rsp.getStatus();
				if (status == 0) {
					LOG.info(link.getUrl() + " indexed successfully");
				}
			} catch (Exception ex) {
				LOG.warn("could not add link: " + link.getTitle());
				LOG.warn(StringTools.getStackTrace(ex));
			}

		}

	}
}
